//
//  HomeEditView.m
//  Fireball
//
//  Created by 任长平 on 2017/12/4.
//  Copyright © 2017年 任长平. All rights reserved.
//

#import "HomeEditView.h"
#import "ChannelCell.h"

@interface ChannelCellSection : UICollectionReusableView
@property(nonatomic, strong)UILabel *titleLabel;
@end

@interface HomeEditView ()<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
>


@property(nonatomic, strong)UIView *titleView;
@property(nonatomic, strong)UILabel *titleLabel;
@property(nonatomic, strong)UIButton *finishButton;
@property(nonatomic, strong)UIButton *cancelButton;

@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, strong)UICollectionViewFlowLayout *flowLayout;

@property(nonatomic, strong)NSArray *titleArray;

@property(nonatomic, strong)NSMutableArray *selectedArray;
@property(nonatomic, strong)NSMutableArray *unSelectedArray;

///是否处于编辑状态
@property(nonatomic, assign)BOOL editing;

@end

@implementation HomeEditView

-(instancetype)initWithFrame:(CGRect)frame{
    if ([super initWithFrame:frame]) {
        self.backgroundColor = [UIColor xm_colorFromRGB:0xF7F8FA];
        self.selectedArray = [NSMutableArray array];
        self.unSelectedArray = [NSMutableArray array];

        self.titleArray = @[@"已选频道",@"未选频道"];
        
        
        self.titleView = [[UIView alloc]init];
        self.titleView.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.titleView];
        
        self.titleLabel = [[UILabel alloc]init];
        self.titleLabel.font = [UIFont xm_font:15.0];
        self.titleLabel.textColor = [UIColor xm_colorFromRGB:0x5D646E];
        [self.titleView addSubview:self.titleLabel];
        
        self.finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.finishButton setTitle:@"编辑" forState:UIControlStateNormal];
        [self.finishButton setTitle:@"完成" forState:UIControlStateSelected];
        [self.finishButton setTitleColor:[UIColor xm_MainColor] forState:UIControlStateNormal];
        self.finishButton.titleLabel.font = [UIFont xm_font:13.0];
        self.finishButton.clipsToBounds = YES;
        self.finishButton.layer.cornerRadius = 21 * 0.5;
        self.finishButton.layer.borderWidth = 1.0;
        [self.finishButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [self.finishButton addTarget:self action:@selector(finishButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        self.finishButton.layer.borderColor = [UIColor xm_MainColor].CGColor;
        [self addSubview:self.finishButton];
        
        self.cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
        self.cancelButton.backgroundColor = XMRandomColor;
        [self addSubview:self.cancelButton];
        
        self.titleLabel.text = @"切换频道";
        
        [self addSubview:self.collectionView];
        
        //添加长按的手势
        UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
        [self.collectionView addGestureRecognizer:longPress];
        
    }
    return self;
}

-(void)setMuneArray:(NSArray *)muneArray{
    _muneArray = muneArray;
    [self.selectedArray removeAllObjects];
    [self.unSelectedArray removeAllObjects];
    
    for (AticleMenu *menu in _muneArray) {
        if (menu.selected) {
            [self.selectedArray addObject:menu];
        }else{
            [self.unSelectedArray addObject:menu];
        }
    }
    [self.collectionView reloadData];
}

- (void)longPress:(UIGestureRecognizer *)longPress {
    //获取点击在collectionView的坐标
    CGPoint point=[longPress locationInView:self.collectionView];
    //从长按开始
    NSIndexPath *indexPath=[self.collectionView indexPathForItemAtPoint:point];
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        //长按手势状态改变
    } else if(longPress.state==UIGestureRecognizerStateChanged) {
        [self.collectionView updateInteractiveMovementTargetPosition:point];
        //长按手势结束
    } else if (longPress.state==UIGestureRecognizerStateEnded) {
        [self.collectionView endInteractiveMovement];
        //其他情况
    } else {
        [self.collectionView cancelInteractiveMovement];
    }
}

-(void)cancelButtonClick{
    [self removeFromSuperview];
}
-(void)finishButtonClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        sender.backgroundColor = [UIColor xm_MainColor];
    }else{
        sender.backgroundColor = [UIColor whiteColor];
    }
    self.editing = sender.selected;
    [self.collectionView reloadData];
}
-(void)deleteItem:(NSInteger)index{
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    ChannelCell *cell = (ChannelCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    cell.menu.selected = NO;
    cell.delBtn.hidden = YES;
    [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];

    AticleMenu * menu = self.selectedArray[index];
    [self.selectedArray removeObject:menu];
    [self.unSelectedArray insertObject:menu atIndex:0];
    NSIndexPath *targetIndexPage = [NSIndexPath indexPathForItem:0 inSection:1];
    [self.collectionView moveItemAtIndexPath:indexPath toIndexPath:targetIndexPage];
    [self refreshDelBtnsTag];
}
/** 刷新删除按钮的tag */
- (void)refreshDelBtnsTag{
    for (ChannelCell *cell in self.collectionView.visibleCells) {
        NSIndexPath *indexpath = [self.collectionView indexPathForCell:cell];
        cell.delBtn.tag = indexpath.item;
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.titleArray.count;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader){
        ChannelCellSection *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ChannelCellSection" forIndexPath:indexPath];
            header.titleLabel.text = self.titleArray[indexPath.section];
        NSLog(@"%@",self.titleArray[indexPath.section]);
        return header;
    }
    return nil;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return self.selectedArray.count;
    }else if (section == 1){
        return self.unSelectedArray.count;
    }
    return 0;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ChannelCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ChannelCell" forIndexPath:indexPath];
    
    cell.editing = self.editing;

    if (indexPath.section == 0) {
        WEAKSELF
        cell.deleteBlock = ^(UIButton *sender) {
            [weakSelf deleteItem:sender.tag];
        };
        cell.delBtn.tag = indexPath.row;
        cell.menu = self.selectedArray[indexPath.row];
    }else if (indexPath.section == 1){
        cell.menu = self.unSelectedArray[indexPath.row];
    }
    return cell;
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREEN_WIDTH-30)/4 -15, 40);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 15;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(collectionView.bounds.size.width, 50);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        if (self.editing) {
            ChannelCell *cell = (ChannelCell *)[collectionView cellForItemAtIndexPath:indexPath];
            cell.menu.selected = YES;
            cell.delBtn.hidden = NO;
            [collectionView reloadItemsAtIndexPaths:@[indexPath]];
            
            [self.unSelectedArray removeObjectAtIndex:indexPath.item];
            [self.selectedArray addObject:cell.menu];
            
            NSIndexPath *targetIndexPage = [NSIndexPath indexPathForItem:self.selectedArray.count -1 inSection:0];
            cell.delBtn.tag = targetIndexPage.item;
            [collectionView moveItemAtIndexPath:indexPath toIndexPath:targetIndexPage];
            
        }
    }
    [self refreshDelBtnsTag];
        
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    ChannelCell *cell = (ChannelCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (indexPath.section == 0) {
        if (cell.menu.selected) {
            return NO;
        }else{
            return YES;
        }
    }
    return NO;
}

-(void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    AticleMenu *object= self.selectedArray[sourceIndexPath.item];
    [self.selectedArray removeObjectAtIndex:sourceIndexPath.item];
    if (destinationIndexPath.section == 0) {
        [self.selectedArray insertObject:object atIndex:destinationIndexPath.item];
    }
    
    [self refreshDelBtnsTag];
}



-(UICollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:ChannelCell.class forCellWithReuseIdentifier:@"ChannelCell"];
        
        [_collectionView registerClass:ChannelCellSection.class
            forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                   withReuseIdentifier:@"ChannelCellSection"];
    }
    return _collectionView;
}

-(UICollectionViewFlowLayout *)flowLayout{
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _flowLayout.minimumLineSpacing = 0;
        _flowLayout.minimumInteritemSpacing = 0;
    }
    return _flowLayout;
}




-(void)layoutSubviews{
    [super layoutSubviews];
    
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(self);
        make.height.mas_equalTo(@44);
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(16);
        make.centerY.mas_equalTo(self.titleView);
    }];
    
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.mas_equalTo(self.titleView);
        make.width.mas_equalTo(self.cancelButton.mas_height);
    }];
    [self.finishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.titleView);
        make.right.mas_equalTo(self.cancelButton.mas_left).offset(-10);
        make.size.mas_equalTo(CGSizeMake(54, 21));
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(self);
        make.top.mas_equalTo(self.titleView.mas_bottom);
    }];
}



@end








@implementation ChannelCellSection
-(instancetype)initWithFrame:(CGRect)frame{
    if ([super initWithFrame:frame]) {
        self.backgroundColor = [UIColor xm_colorFromRGB:0xF7F8FA];

        self.titleLabel = [[UILabel alloc] init];
        self.titleLabel.font = [UIFont xm_font:17.f];
        self.titleLabel.textColor = [UIColor xm_colorFromRGB:0x5D646E];
        [self addSubview:self.titleLabel];
        
    }
    return self;
    
}
-(void)layoutSubviews{
    [super layoutSubviews];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 16, 0, 0));
    }];
}
@end
